﻿
//function HeartBeat() {
//    bee.PostData("/AuthMain/HeartBeat.bee", null);
//}

function HeartBeat() {
    bee.PostData("/BeeMessage/UnreadCount.bee", null, function(count) {
        if (count > 0) {
            $("#beeMessage").show().find("span").html(count).css("color", "red");
        }
        else {
            $("#beeMessage").hide();
        }
    });
}

function toLogin() {
    //window.location.href = "/AuthMain/Login.bee";
    $("#innerLogin").trigger("click");
}



/**
* 带文件上传的ajax表单提交
* @param {Object} form
* @param {Object} callback
*/
function iframeCallback(form, callback) {
    var $form = $(form), $iframe = $("#callbackframe");
    if (!$form.valid()) { return false; }

    if ($iframe.size() == 0) {
        $iframe = $("<iframe id='callbackframe' name='callbackframe' src='about:blank' style='display:none'></iframe>").appendTo("body");
    }
    if (!form.ajax) {
        $form.append('<input type="hidden" name="ajax" value="1" />');
    }
    form.target = "callbackframe";

    _iframeResponse($iframe[0], callback || bee.ajaxDone);
}
function _iframeResponse(iframe, callback) {
    var $iframe = $(iframe), $document = $(document);

    $document.trigger("ajaxStart");

    $iframe.bind("load", function(event) {
        $iframe.unbind("load");
        $document.trigger("ajaxStop");

        if (iframe.src == "javascript:'%3Chtml%3E%3C/html%3E';" || // For Safari
			iframe.src == "javascript:'<html></html>';") { // For FF, IE
            return;
        }

        var doc = iframe.contentDocument || iframe.document;

        // fixing Opera 9.26,10.00
        if (doc.readyState && doc.readyState != 'complete') return;
        // fixing Opera 9.64
        if (doc.body && doc.body.innerHTML == "false") return;

        var response;

        if (doc.XMLDocument) {
            // response is a xml document Internet Explorer property
            response = doc.XMLDocument;
        } else if (doc.body) {
            try {
                response = $iframe.contents().find("body").text();
                response = bee.jsonEval(response);
            } catch (e) { // response is html document or plain text
                response = doc.body.innerHTML;
            }
        } else {
            // response is a xml document
            response = doc;
        }

        callback(response);
    });
}


function reloadDialog(formId) {
    if (!formId) {
        var $box = $.pdialog.getCurrent();

        formId = $("form", $box).attr("Id")
    }

    var form = "#" + formId;
    var $form = $(form);
    if ($form.valid()) {
        $("input[name='pageNum']", $form).val(1);
        $("input[name='recordCount']", $form).val(0);
        $.pdialog.reload($form.attr('action'), { data: $form.serializeArray() });
    }
}

function divLoad(form, $div) {
    var $form = $(form);
    if ($div) {
        var $box = $div;
        $box.ajaxUrl({
            type: "POST", url: $form.attr("action"), data: $form.serializeArray(), callback: function() {
                $box.find("[layoutH]").layoutH();
            }
        });
    }
    return false;
}

function ajaxTodo(url, callback) {
    var formId = getCurrentFormId();
    var form = "#" + formId;
    var $callback = callback;
    if (!$.isFunction($callback)) $callback = eval('(' + callback + ')');
    $.ajax({
        type: 'POST',
        url: url,
        dataType: "json",
        cache: false,
        success: function(data) {
            if (data.status) {
                if ($.isFunction($callback)) {
                    $callback(data.result);
                }
                else {
                    var refreshFlag = true;
                    var formInNavTab = $(form, navTab.getCurrentPanel());
                    if (formInNavTab.length) {
                        refreshFlag = !formInNavTab.hasClass("noRefresh");
                        if (!refreshFlag) {
                            navTab.closeCurrentTab();
                        }
                    }

                    if (refreshFlag) {
                        autoList(formId);
                    }
                }

                alertMsg.correct("操作成功！");


            } else {
                alertMsg.error(data.message);
            }
        },
        error: bee.ajaxError
    });

}

function clearEmptyTr(table) {
    var tbody = table.find("tbody");
    var trs = tbody.find('>tr');
    var removeTrs = [];
    trs.each(function(i) {
        var emptyFlag = true;
        $(":text.required", $(this)).each(function(i) {
            if ($(this).val() != '') {
                emptyFlag = false;
            }
        });
        if (emptyFlag) {
            removeTrs.push(this);
        }
    });

    $(removeTrs).each(function(i) { $(this).remove(); });
    trs = tbody.find('>tr');
    if (trs.length == 0) {
        return false;
    }
    return true;
}

function autoSave(formId) {
    if (!formId) formId = getCurrentFormId();
    var form = "#" + formId;
    var $form = $(form);
    if ($form.valid()) {
        var itemNum = $("input[name=bee_itemNum]", $form);
        if (itemNum.length && itemNum.val() == 0) {
            alertMsg.error("无任何明细。");
            return;
        }
        bee.PostData($form.attr('action'), $form.serializeArray(), function(data) {
            var refreshFlag = true;
            var formInNavTab = $(form, navTab.getCurrentPanel());
            if (formInNavTab.length) {
                refreshFlag = !formInNavTab.hasClass("noRefresh");
            }
            if (refreshFlag) {
                autoList(getCurrentFormId());
                $.pdialog.closeCurrent();
                
            }
            else {
                navTab.closeCurrentTab();
            }

            alertMsg.correct("操作成功！");
        });
    }
}


function getCurrentFormId(box) {
    $box = $(box);
    if ($box.length == 0) {
        $box = $(navTab.getCurrentPanel());
    }

    return $("form", $box).attr("Id");
}

function autoList(formId, orderField, orderDirection) {
    if (!formId) formId = getCurrentFormId();
    var form = "#" + formId;
    var $form = $(form);
//    if (orderField) {
//        $("input[name='orderField']", $form).val(orderField);
//        $("input[name='orderDirection']", $form).val(orderDirection);
//    }
    if ($form.length && $form.valid()) {
        $("input[name='pageNum']", $form).val(1);
        $("input[name='recordCount']", $form).val(0);

        navTab.reload($form.attr('action'), { data: $form.serializeArray() });
        return false;
    }
}

//function subJumpTo(formId, pageNum, src)

function dialogJumpTo(pageNum, src) {
    var $box = $.pdialog.getCurrent();
    var $form = $("form", $box);
    if (pageNum == 0) {
        var $inputBox = $(src).siblings(":text");
        pageNum = $inputBox.val();
    }

    $("input[name='pageNum']", $form).val(pageNum);
    $.pdialog.reload($form.attr('action'), { data: $form.serializeArray() });
}

function autoJumpTo(pageNum, src) {
    var formId = getCurrentFormId();
    var form = "#" + formId;
    var $form = $(form);
    if (pageNum == 0) {
        var $inputBox = $(src).siblings(":text");
        pageNum = $inputBox.val();
    }

    $("input[name='pageNum']", $form).val(pageNum);

    navTab.reload($form.attr('action'), { data: $form.serializeArray() });
    return false;
}

function dwzExport() {
    function _doExport($this) {
        var $p = $this.attr("targetType") == "dialog" ? $.pdialog.getCurrent() : navTab.getCurrentPanel();
        var $form = $("#pagerForm", $p);
        var url = $this.attr("href");
        window.location = url + (url.indexOf('?') == -1 ? "?" : "&") + $form.serialize();
    }

    return this.each(function() {
        var $this = $(this);
        $this.click(function(event) {
            var title = $this.attr("title");
            if (title) {
                alertMsg.confirm(title, {
                    okCall: function() { _doExport($this); }
                });
            } else { _doExport($this); }

            event.preventDefault();
        });
    });
}

/**
* 处理div上的局部查询, 会重新载入指定div
* @param {Object} form
*/
function divSearch(form, rel) {
    var $form = $(form);
    if (form["pageNum"]) form["pageNum"].value = 1;
    if (rel) {
        var $box = $("#" + rel);
        $box.ajaxUrl({
            type: "POST", url: $form.attr("action"), data: $form.serializeArray(), callback: function() {
                $box.find("[layoutH]").layoutH();
            }
        });
    }
    return false;
}

/**
* 
* @param {Object} args {pageNum:"",numPerPage:"",orderField:"",orderDirection:""}
* @param String formId 分页表单选择器，非必填项默认值是 "pagerForm"
*/
function _getPagerForm($parent, args) {
    var form = $("Form", $parent).get(0);

    if (form) {
        if (args["pageNum"]) form["pageNum"].value = args["pageNum"];
        if (args["numPerPage"]) form["numPerPage"].value = args["numPerPage"];
        if (args["orderField"]) form["orderField"].value = args["orderField"];
        if (args["orderDirection"] && form["orderDirection"]) form["orderDirection"].value = args["orderDirection"];
    }

    return form;
}
/**
* 处理navTab中的分页和排序
* targetType: navTab 或 dialog
* rel: 可选 用于局部刷新div id号
* data: pagerForm参数 {pageNum:"n", numPerPage:"n", orderField:"xxx", orderDirection:""}
* callback: 加载完成回调函数
*/
function dwzPageBreak(options) {
    var op = $.extend({ targetType: "navTab", rel: "", data: { pageNum: "", numPerPage: "", orderField: "", orderDirection: "" }, callback: null }, options);
    var $parent = op.targetType == "dialog" ? $.pdialog.getCurrent() : navTab.getCurrentPanel();

    if (op.rel) {
        var $box = $parent.find("#" + op.rel);
        var form = _getPagerForm($box, op.data);
        if (form) {
            $box.ajaxUrl({
                type: "POST", url: $(form).attr("action"), data: $(form).serializeArray(), callback: function() {
                    $box.find("[layoutH]").layoutH();
                }
            });
        }
    } else {
        var form = _getPagerForm($parent, op.data);
        var params = $(form).serializeArray();

        if (op.targetType == "dialog") {
            if (form) $.pdialog.reload($(form).attr("action"), { data: params, callback: op.callback });
        } else {
            if (form) navTab.reload($(form).attr("action"), { data: params, callback: op.callback });
        }
    }
}
/**
* 处理navTab中的分页和排序
* @param args {pageNum:"n", numPerPage:"n", orderField:"xxx", orderDirection:""}
* @param rel： 可选 用于局部刷新div id号
*/
function navTabPageBreak(args, rel) {
    dwzPageBreak({ targetType: "navTab", rel: rel, data: args });
}
/**
* 处理dialog中的分页和排序
* 参数同 navTabPageBreak 
*/
function dialogPageBreak(args, rel) {
    dwzPageBreak({ targetType: "dialog", rel: rel, data: args });
}


function autoChangePageSize(combo) {
    var formId = getCurrentFormId();
    var navTabId;
    var $this = $(combo);
    var form = "#" + formId;
    var $form = $(form);
    $("input[name='pageNum']", $form).val(1);
    $("input[name='pageSize']", $form).val($this.val());

    navTab.reload($form.attr('action'), { data: $form.serializeArray(), navTabId: navTabId });
    return false;
}

function validShowAlertMsgError(valid) {
    var msg = [];
    for (var i = 0; valid.errorList[i]; i++) {
        var error = valid.errorList[i];
        msg.push(error.message);
        valid.settings.highlight && valid.settings.highlight.call(valid, error.element, valid.settings.errorClass, valid.settings.validClass);
    }

    if (valid.settings.unhighlight) {
        for (var i = 0, elements = valid.validElements(); elements[i]; i++) {
            valid.settings.unhighlight.call(valid, elements[i], valid.settings.errorClass, valid.settings.validClass);
        }
    }
    if (valid.errorList.length != 0) {
        alertMsg.info(msg.join("</br>"));
    }
}

function autoFill(form, json) {
    form[0].reset();
    $(":input", form).each(function() {
        $this = $(this);
        var itemValue = new String(json[$this.attr("name")]);
        itemValue = itemValue.toString();
        if (itemValue.indexOf("/Date(") >= 0
            && itemValue.indexOf("+") > 0) {
            var indexadd = itemValue.indexOf("+");
            var tempstr = itemValue.substring(6, indexadd);
            var result = new Date();
            result.setTime(tempstr);
            itemValue = result.formatDate("yyyy-MM-dd HH:mm:ss");
        }

        if (itemValue && itemValue != "undefined" && itemValue != "null") {
            switch (this.type) {
                case 'checkbox':
                case 'radio':
                    if ($this.val() == itemValue) {
                        $this.attr("checked", itemValue);
                    }
                    else {
                        if ($this.attr("checked")) {
                            $this.removeAttr("checked");
                        }
                    }
                    break;
                case 'hidden':
                case 'password':
                case 'textarea':
                case 'text':
                case 'select-one':
                    $this.val(itemValue);
                    break;
            }
        }
    });
}

/**
* http://www.uploadify.com/documentation/uploadify/onqueuecomplete/	
*/
function uploadifyQueueComplete(queueData) {

    var msg = "The total number of files uploaded: " + queueData.uploadsSuccessful + "<br/>"
		+ "The total number of errors while uploading: " + queueData.uploadsErrored + "<br/>"
		+ "The total number of bytes uploaded: " + queueData.queueBytesUploaded + "<br/>"
		+ "The average speed of all uploaded files: " + queueData.averageSpeed;

    if (queueData.uploadsErrored) {
        alertMsg.error(msg);
    } else {
        alertMsg.correct(msg);
    }
}
/**
* http://www.uploadify.com/documentation/uploadify/onuploadsuccess/
*/
function uploadifySuccess(file, data, response) {
    
    alert(data);
    alert(file);
    alert(response);
}

/**
* http://www.uploadify.com/documentation/uploadify/onuploaderror/
*/
function uploadifyError(file, errorCode, errorMsg) {
    alertMsg.error(errorCode + ": " + errorMsg);
}